package burubaka.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import burubaka.meta.TipsterMeta;
import burubaka.model.Tipster;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class TipsterService {

	private static final Logger log = Logger.getLogger(TipsterService.class.getName());

	private TipsterMeta meta = new TipsterMeta();

	/**
	 * キー検索
	 * 
	 * @param key
	 * @return Tipster
	 */
	public Tipster findByKey(Key key) {
		return Datastore.query(Tipster.class, key).asSingle();
	}

	/**
	 * ユーザーIDで検索
	 * 
	 * @param userId
	 * @return Tipster
	 */
	public Tipster findByUser(String userId) {
		return Datastore.query(meta).filter(meta.userId.equal(userId)).asSingle();
	}

	/**
	 * ポストで検索
	 * 
	 * @param post
	 * @return Tipster
	 */
	public Tipster findByPost(String post) {
		return Datastore.query(meta).filter(meta.post.equal(post)).asSingle();
	}

	/**
	 * 全検索
	 * 
	 * @return List<Tipster>
	 */
	public List<Tipster> findAll() {
		return Datastore.query(meta).asList();
	}

	/**
	 * ユーザーで検索
	 * 
	 * @return Tipster
	 */
	public Tipster getTipster() {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		return Datastore.query(meta).filter(meta.userId.equal(user.getUserId())).asSingle();
	}

	/**
	 * ユーザーIDで予想屋情報をJSON形式で取得
	 * 
	 * @param userId
	 * @return String
	 */
	public String getJSONByUserId(String userId) {
		return meta.modelToJson(this.findByUser(userId));
	}

	/**
	 * 登録
	 * 
	 * @param model
	 * @return Tipster
	 */
	public Tipster regist(Tipster model) {

		Transaction tx = Datastore.beginTransaction();
		Datastore.put(model);
		tx.commit();

		return model;
	}

	/**
	 * 登録
	 * 
	 * @param input
	 * @param raceInfo
	 * @return boolean
	 */
	public boolean regist(Map<String, Object> input, Tipster model) {
		Map map = JSON.decode((String) input.get("tipster"), HashMap.class);
		BeanUtil.copy(map, model);
		regist(model);
		return true;
	}

	/**
	 * 削除
	 * 
	 * @param model
	 * @return boolean
	 */
	public boolean delete(Tipster model) {
		Transaction tx = Datastore.beginTransaction();
		Datastore.delete(model.getKey());
		tx.commit();
		return true;
	}

}
